<?php
namespace control;
/*
*试卷管理类
*/

class paperManagementClass extends adIndexClass
{
    private const page = 'paperManagement';
    private const tableMx = 'paper_library_detail';
    private const table = 'paper_library';
    private const title = '试卷管理';
    public array $stateOption = ['草稿', '未开始', '进行中', '已结束'];
    public array $typeOption = ['单选题', '多选题', '判断题', '主观题'];
    public array $itemWord = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'L'];

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('topic.table.orderNo') => text(array("name" => "orderNo")),
                    L('topic.table.paperName')     => text(array("name" => "name")),
                    L('topic.table.paperType') => select(array("name" => "type", 'option' => ['练习', '考试'])),
                ],
                [
                    L('topic.table.startTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    L('report.table.state') => select(array("name" => "state", "option" => $this->stateOption)),
                ]
            ]
        ],1);
        //返回
        if(!$isAsync){
            return $html;
        }else{
            return json_encode(['html'=>$html],320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>".L('job.model.edit')."</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">".L('topic.table.del')."</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html,layout: 'pop',toolButton: $button));
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'scoreSearch':
                $tr = [
                    'staff'      => [
                        'name'  => L('staffProfiles.table.name'),
                        'width' => 150,
                    ],
                    'department' => [
                        'name'  => L('staffProfiles.table.department'),
                        'width' => 200,
                    ],
                    'job'  => [
                        'name'  => L('staffProfiles.table.job'),
                        'width' => 200,
                    ],
                    'startTime'         => [
                        'name'  => L('topic.table.testStart'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'commitTime'          => [
                        'name'  => L('recruitment.table.commitTime'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'second'          => [
                        'name'  => L('topic.table.useTime'),
                        'width' => 150,
                    ],
                    'score'          => [
                        'name'  => L('topic.table.getScore'),
                        'width' => 120,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => L('staffProfiles.table.stateText'),
                        'width' => 120,
                    ],
                    'mx'          => [
                        'name'  => L('topic.table.answerInfo'),
                        'width' => 200,
                    ]
                ];
                break;
            case 'topicSearch':
                $tr = [
                    'topicType'      => [
                        'name'  => L('topic.table.questionsType'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'title' => [
                        'name'  => L('topic.table.stem'),
                        'width' => 250,
                    ],
                    'itemText'  => [
                        'name'  => L('topic.table.option'),
                        'width' => 300,
                    ],
                    'answerText'         => [
                        'name'  => L('topic.table.answer'),
                        'width' => 300,
                    ],
                    'score'          => [
                        'name'  => L('topic.table.score'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'rate'          => [
                        'name'  => L('topic.table.rightRate'),
                        'width' => 250,
                    ],
                    'seeText'          => [
                        'name'  => L('topic.table.answerInfo'),
                        'width' => 120,
                    ]
                ];
                break;
            case 'topicSearchList':
                $tr = [
                    'topicType'      => [
                        'name'  => L('topic.table.questionsType'),
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'title' => [
                        'name'  => L('topic.table.stem'),
                        'width' => 200,
                    ],
                    'itemText'  => [
                        'name'  => L('topic.table.option'),
                        'width' => 250,
                    ],
                    'answerText'         => [
                        'name'  => L('topic.table.answer'),
                        'width' => 250,
                    ],
                    'score'          => [
                        'name'  => L('topic.table.score'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'list'          => [
                        'name'  => L('topic.table.topicList'),
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'rate'          => [
                        'name'  => L('topic.table.rightRate'),
                        'width' => 200,
                    ],
                    'seeText'          => [
                        'name'  => L('topic.table.answerInfo'),
                        'width' => 120,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => L('topic.table.orderNo'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => L('topic.table.paperName'),
                        'width' => 150,
                    ],
                    'type'  => [
                        'name'  => L('topic.table.paperType'),
                        'width' => 100,
                    ],
                    'topicNum'         => [
                        'name'  => L('topic.table.topicNum'),
                        'width' => 100,
                    ],
                    'score'          => [
                        'name'  => L('topic.table.totalScore'),
                        'width' => 100,
                    ],
                    'passMark'          => [
                        'name'  => L('topic.table.passScore'),
                        'width' => 100,
                    ],
                    'startTime'          => [
                        'name'  => L('topic.table.testStart'),
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'endTime'          => [
                        'name'  => L('topic.table.testEnd'),
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'minute'          => [
                        'name'  => L('topic.table.minuteUnit'),
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'beTested'          => [
                        'name'  => L('topic.table.beTested'),
                        'width' => 100,
                    ],
                    'tested'          => [
                        'name'  => L('topic.table.tested'),
                        'width' => 100,
                    ],
                    'waitNum'          => [
                        'name'  => L('topic.table.waitNum'),
                        'width' => 100,
                    ],
                    'state'          => [
                        'name'  => L('staffProfiles.table.stateText'),
                        'width' => 100,
                    ],
                ];
        }
        return $tr;
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//试卷编号
            "name" => $this->post('name'),//试卷标题
        );
        //全等查询数组
        $equal = array(
            "type" => $this->post('type'),//试卷标题
        );
        $and = "";
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and date(startTime) >='{$timeArr[0]}' and  date(startTime) <='{$timeArr[1]}'";
        }

        switch ($this->post('state')) {
            case '草稿':
                $and .= " and state = '草稿'";
                break;
            case '未开始':
                $and .= " and state = '已发布' and UNIX_TIMESTAMP(startTime) > UNIX_TIMESTAMP()";
                break;
            case '进行中':
                $and .= " and state = '已发布' and UNIX_TIMESTAMP(startTime) <= UNIX_TIMESTAMP() and UNIX_TIMESTAMP(endTime) >= UNIX_TIMESTAMP()";
                break;
            case '已结束':
                $and .= " and state = '已发布' and UNIX_TIMESTAMP(endTime) < UNIX_TIMESTAMP()";
                break;
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('topic.table.paperInfo'), "click" => "newIframe('" . L('topic.table.paperInfo') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //应考人数
            $testTotalPeople = static::total(array('table' => 'paper_people', 'where' => " and orderId = '$array[id]'"));
            //已考试人数
            $testPeople = static::total(array('table' => 'topic_answer_record', 'where' => " and paperId = '$array[id]'"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "topicNum":
                        //题目数量
                        $topicNum = static::total(array('table' => self::tableMx, 'where' => " and orderId = '$array[id]'"));
                        $row[] = $topicNum;
                        break;
                    case "score":
                        //总分
                        $score = find(array('table' => self::tableMx, "where" => " orderId = '$array[id]'", 'sum' => "score"));
                        $row[] = $score;
                        break;
                    case "beTested":
                        $row[] = $testTotalPeople;
                        break;
                    case "tested":
                        $row[] = $testPeople;
                        break;
                    case "waitNum":
                        $row[] = $testTotalPeople - $testPeople;
                        break;
                    case "state":
                        $row[] = $this->showState($array['state'], $array['startTime'], $array['endTime']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton,"width" => 120),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    private function showState($state, $startTime,$endTime): string
    {
        if ($state == '已发布') {
            if (time() > strtotime($endTime)) {
                return L('topic.table.ended');
            } elseif (time() >= strtotime($startTime) && time() <= strtotime($endTime)) {
                return L('topic.table.handing');
            } else {
                return L('topic.table.notStarted');
            }
        }
        return $state;
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . L('topic.table.paperName')."：" => text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                    must . L('topic.table.paperType')."：" => radio(["name" => "type", 'value' => ['练习', '考试'], "checked" => $info['type'] ?: '练习']),
                ],
                [
                    must . L('topic.table.limitTime')."：" => text(["name" => "chooseDate", 'laydate' => ['range' => '~', 'type' => 'datetime'], "value" => $info['id'] ? ($info['startTime'] . ' ~ ' . $info['endTime']) : '']),
                ],
                [
                    must . L('topic.table.minute')."：" => text(["name" => "minute", 'unit' => '分钟', "value" => $info['minute']]).
                        componentClass::tipComponent('练习类型无需填写考试时长'),
                    L('topic.table.passScore')."：" => text(["name" => "passMark", 'class' => 'text', "value" => $info['passMark']]),
                ],
                [
                    must . L('topic.table.answerType')."：" => radio(["name" => "answerType", 'value' => ['整卷答题', '逐题答题'], "checked" => $info['answerType']]),
                    must . L('topic.table.isRandom')."：" => radio(["name" => "isRandom", 'value' => ['是', '否'], "checked" => $info['isRandom']]),
                ],
                [
                    L('staffProfiles.table.text')."：" => textarea(["name" => "text", "value" => $info['text']]),
                ],
            ],
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $timeArr = $this->post('chooseDate') ? explode(' ~ ', $this->post('chooseDate')) : [];
        $field = [
            'name' => $this->post('name'),
            'type' => $this->post('type'),
            'startTime' => $timeArr[0],
            'endTime' => $timeArr[1],
            'minute' => $this->post('minute'),
            'passMark' => $this->post('passMark'),
            'answerType' => $this->post('answerType'),
            'isRandom' => $this->post('isRandom'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'name' => L('topic.table.paperName'),
            'type' => L('topic.table.paperType'),
            'startTime' => L('topic.table.testTime'),
            'endTime' => L('topic.table.testTime'),
            'minute' => L('topic.table.minute'),
            'answerType' => L('topic.table.answerType'),
            'isRandom' => L('topic.table.isRandom'),
        ];
        $rules = [
            'name' => 'required',
            'type' => 'required',
            'startTime' => 'required',
            'endTime' => 'required',
            'minute' => 'required',
            'answerType' => 'required',
            'isRandom' => 'required',
        ];
        $field['minute'] = $field['type'] === '练习' ? floor((strtotime($field['endTime']) - strtotime($field['startTime'])) / 60) : $field['minute'];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.paper_edit_permission');
        } elseif (strtotime($field['endTime']) <= time()) {
            $json['warn'] = L('topic.table.testTime_permission');
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'TP' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'isMessage' => 0,
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $field['name'], $id], L('topic.table.paper_edit_log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('topic.table.no_paper');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                'menu' => [
                    'detail' => L('topic.table.baseInfo'),
                    'topic' => L('topic.table.testInfo'),
                    'score' => L('topic.table.achievementInfo'),
                ]
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('topic.table.release'),
                    "type" => "点击事件",
                    "title" => L('topic.table.release'),
                    'fun' => "layer('" . self::page . "','stateSwitch',{id:'" . $info['id'] . "'})",
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮
                $button[] = [
                    "name" => L('topic.table.preview'),
                    "type" => "点击事件",
                    "title" =>L('topic.table.preview'),
                    'fun' => "window.open('" . root . "control/adIndex.html?cla={$this->get('cla')}&fun=previewPaper&method=preview&id={$info['id']}')"
                ];
                //按钮
                $button[] = [
                    "name" => L('topic.table.edit'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
                ];

            } else {
                //按钮
                $button[] = [
                    "name" => L('topic.table.preview'),
                    "type" => "点击事件",
                    "title" => L('topic.table.preview'),
                    'fun' => "window.open('" . root . "control/adIndex.html?cla={$this->get('cla')}&fun=previewPaper&method=preview&id={$info['id']}&list=1')",
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, 'del') && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => L('topic.table.del'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, 'cancel') && $info['state'] == '已发布') {
                //按钮
                $button[] = [
                    "name" => L('salary.table.cancel'),
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],

                ];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                "基本信息" => array(
                    array(
                        L('topic.table.orderNo') => $info['orderNo'],
                        L('topic.table.paperName') => $info['name'],
                        L('topic.table.testTime') => $info['startTime'] . ' ~ ' . $info['endTime'],
                    ),
                    array(
                        L('topic.table.paperType') => $info['type'],
                        L('topic.table.minuteUnit') => $info['minute'],
                        L('topic.table.passScore') => $info['passMark'],
                        L('topic.table.answerType') => $info['answerType'],
                    ),
                    array(
                        L('topic.table.isRandom') => $info['isRandom'],
                        L('department.table.creator') => self::findStaff($info['stid']),
                        L('department.table.creatTime') => $info['time'],
                        L('staffProfiles.table.stateText') => $info['state'],
                    ),
                ),
            ));


            $referenceRateText = $this->referRateText($info);//参考率
            $passRateText = $this->passRateText($info);//合格率
            $scoreText = $this->scoreDistribution($info);//成绩分布

            $distribution = L('topic.table.distribution');
            $referenceRateTitle = L('topic.table.referenceRate');
            $passRateTitle = L('topic.table.passRate');
            //生成页面
            $data['html'] .= <<<efo
  <script src='{$this->root}static/javascript/echarts.min.js'></script>
<div style="margin-top: 50px">
<ul>
    <li class="quarter left vertical-line" style="width: 33%;padding: 0 20px"><p><h3>$referenceRateTitle</h3></p><div style="width: 100%;height: 300px">$referenceRateText</div></li>
    <li class="quarter left vertical-line" style="width: 33%;padding: 0 20px"><p><h3>$passRateTitle</h3></p><div style="width: 100%;height: 300px">$passRateText</div></li>
    <li class="quarter left vertical-line" style="width: 33%;padding: 0 20px"><p><h3>$distribution</h3></p><div style="width: 100%;height: 300px">$scoreText</div></li>
</ul>

<script>

</script>


</div>

efo;

            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'isMessage'=>0
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此试卷';
        } elseif ($info['state'] != '已发布') {
            $json['warn'] = '此试卷不是已发布状态，无需撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));

            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                delete(array('table' => 'message', 'where' => "typeId = '$info[id]'"));
                delete(array('table' => 'topic_answer_record', 'where' => "paperId = '$info[id]'"));
                delete(array('table' => 'topic_answer_record_detail', 'where' => "paperId = '$info[id]'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . "撤回了" . self::title . "id：【" . $id . '】，【'.$info['name'].'】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 成绩分布
     * @param $info
     * @return string|void
     */
    public function scoreDistribution($info)
    {
        $nameData = [
            ['name' => '60分以下', 'min' => 0, 'max' => 60],
            ['name' => '60-70', 'min' => 60, 'max' => 70],
            ['name' => '70-80', 'min' => 70, 'max' => 80],
            ['name' => '80-90', 'min' => 80, 'max' => 90],
            ['name' => '90-100', 'min' => 90, 'max' => 0]];
        $title = [];
        foreach ($nameData as $array) {
            $where = '';
            if ($array['min'] > 0) {
                $where .= " and score >= $array[min]";
            }
            if ($array['max'] > 0) {
                $where .= " and score < $array[max]";
            }
            $num = static::total(array('table' => 'topic_answer_record', 'where' => " and isCommit = 1 and paperId = '$info[id]' {$where}"));
            $xData[] = $num;
            $title[] = $array['name'];
        }
        return $this->barCharts(array(
            'name' => $title,
            'series' => [
                [
                    'name' => L('topic.table.people'),
                    'data' => $xData,
                ]
            ]
        ));
    }

    /**
     * 参考率
     * @param $info
     * @return string|void
     */
    public function referRateText($info)
    {
        if ($info['state'] != '已发布') {
            $referenceRate = 0;
        } else {
            //总人数
            $people = static::total(['table' => 'paper_people', 'where' => " and orderId = '$info[id]'"]);
            $result = find(array('table' => 'topic_answer_record', 'where' => " isCommit = 1 and paperId = '$info[id]'"));
            $totalNum = count($result['array']);//已提交人数
            $referenceRate = $people > 0 ? floor(($totalNum / $people) * 100) / 100 : 0;
        }
        $option = [
            "series" => [
                [
                    'name' =>  L('topic.table.referenceRate'),
                    'data' => $referenceRate, //不能大于1
                ],
            ]
        ];
        return $this->liquidfill($option);
    }

    public function passRateText($info)
    {
        if ($info['state'] != '已发布') {
            $passRate = 0;
        } else {
            $result = find(array('table' => 'topic_answer_record', 'where' => " isCommit = 1 and paperId = '$info[id]'"));
            $passNum = 0;//合格人数
            $totalNum = 0;//已提交人数
            foreach ($result['array'] as $array) {
                $totalNum++;
                if ($array['state'] == '合格') {
                    $passNum++;
                }
            }
            $passRate = $totalNum > 0 ? floor(($passNum / $totalNum) * 100) / 100 : 0;
        }
        $option = [
            "series" => [
                [
                    'name' => L('topic.table.passRate'),
                    'data' => $passRate, //不能大于1
                ],
            ]
        ];
        return $this->liquidfill($option);
    }

    /**
     * 发布
     */
    public function stateSwitch()
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                L('topic.table.tip')."：" => L('topic.table.isPublish'),
            ),
        )));
        //返回
        return $this->layer(array("title" => L('topic.table.release'), "height" => 165, "html" => $html));
    }

    /**
     * 发布
     */
    public function stateSwitchEdit()
    {
        $info = query(self::table, " id ='{$this->post('id')}'");
        $score = find(array('table' => self::tableMx, "where" => " orderId = '$info[id]'", 'sum' => "score"));
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('topic.table.paper_edit_permission');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('topic.table.no_paper');
        } elseif ($info['state'] == '已发布') {
            $json['warn'] = L('topic.table.published');
        } elseif (!static::total(array('table' => self::tableMx, 'where' => " and orderId = '$info[id]'"))) {
            $json['warn'] = L('topic.table.paperWithoutTopic');
        } elseif ($score < $info['passMark']) {
            $json['warn'] = L('topic.table.continueAdd');
        } else {
            $json['warn'] = update(array('table' => self::table, 'field' => ['state' => '已发布'], 'where' => " id = '$info[id]'"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {

                //给参加考试的人员发送消息
                if (strtotime($info['startTime']) < time() && strtotime($info['endTime']) > time()) {
                    //考试开始时间内
                    $member = find(array('table' => 'paper_people', 'where' => " orderId = '$info[id]' order by list asc"));
                    if (is_array($member['array'])) {
                        foreach ($member['array'] as $array) {
                            message(array(
                                "stid" => $array['stid'],
                                "type" => "考试试卷",
                                "typeId" => $info['id'],
                                "text" => str_replace(['{{name}}'], [$info['name']], L('topic.table.papaerMsg')),
                                'targetCla' => 'beTested',
                                'targetFun' => 'home',
                            ));
                        }
                    }
                    update(array('table' => 'paper_library', 'field' => ['isMessage' => 1], 'where' => " id = '$info[id]'"));
                }

                //添加日志
                $text = str_replace(['{{staffName}}', '{{name}}', '{{id}}'], [$this->control['name'], $info['name'], $info['id']], L('topic.table.publish_text'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = L('topic.table.publishSuc');
                $json['href'] = root . 'control/adIndex.html?cla=' . self::page . '&fun=detail&id=' . $info['id'];
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function topicOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('topic.table.topicType') => select(array("name" => "type", "option" => explode('，', para('topicLibraryOption')))),
                    L('topic.table.topicName')   => text(array("name" => "name")),
                    L('topic.table.questionsType') => select(array("name" => "topicType", 'option' => $this->typeOption)),
                ],
                [
                    L('topic.table.stem')  => text(array("name" => "text")).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 试卷试题列表
     */
    public function topic()
    {
        $html = $this->topicOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','addMx',{id:'" . $this->get('id') . "'})\" class='spanButton'>" . L('topic.table.formTopic') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {act:'delTopic',id:'" . $this->get('id') . "'})\">" . L('topic.table.del') . "</span>\n";
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function topicSearch()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");

        $where = " and a.orderId = '$id'";
        $and = '';
        $like = [
            'c.name' => $this->post('name'),
            'b.title' => $this->post('text'),
        ];
        $equal = [
            'b.topicType' => $this->post('topicType'),
            'c.type' => $this->post('type'),
        ];
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'a.list asc,a.`time`',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page = $this->page([
            'field' => "b.*,a.id,a.score,a.list,a.orderId as paperId,a.topicLibraryMxId",
            "table" => "paper_library_detail as a join topic_library_detail as b on a.topicLibraryMxId = b.id join topic_library as c on b.orderId = c.id",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ]);
        //获取自定义字段参数
        if ($info['isRandom'] == '是') {
            $installSearch = $this->installSearch();
        } else {
            $installSearch = $this->installSearch(self::page.'-topicSearchList');
        }
        $body          = [];
        //表格控件区
        $liButton = array($this->checkAll("topicForm", "topicId"));
        $obj = new topicLibraryClass();
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "topicId", "value" => $array['id']),
            );
            $res = $obj->showItemAndAnswer($array);
            $itemText = $res['itemText'];
            $answerText = $res['answerText'];
            $recordNum = static::total(array('table' => 'topic_answer_record_detail', 'where' => " and topicLibraryMxId = '$array[topicLibraryMxId]' and paperId = '$array[paperId]'"));
            $seeText = '';//查看
            $rate = '';//正确率
            $lefWidth = 0;
            $rightWidth = 100;
            if ($recordNum > 0) {
                $result = $this->calculateRate($array['paperId'], $array['topicLibraryMxId']);
                $rightRate = 0;
                if ($result['totalNum'] > 0) {
                    $lefWidth = $rightRate = $result['totalNum'] > 0 ? floor(($result['rightNum'] / $result['totalNum']) * 100) : 0;
                    $rightWidth = 100 - $lefWidth;
                }

                $rate = "<div style='width: 80px;height: 19px;position: relative;background-color: white;line-height: 19px;'><div style='position: absolute;left: 50%;margin-left: -20px;color: white;'>{$rightRate}%</div><div class='left-progress' style='width: {$lefWidth}%;'></div><div style='width: {$rightWidth}%;' class='right-progress'></div></div>";
                $seeText = "<span style='color: #4C9CFB;cursor:pointer;' onclick=\"window.open('" . root . "control/adIndex.html?cla=paperManagement&fun=seePaperRecord&method=record&topicId={$array['topicLibraryMxId']}&id={$array['paperId']}')\">查看</span>";
            }
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "title":
                        $row[] = html_entity_decode($array['title'], ENT_QUOTES);
                        break;
                    case "itemText":
                        $row[] = $itemText;
                        break;
                    case "answerText":
                        $row[] = $answerText;
                        break;
                    case "score":
                        $row[] = text(array('name' => 'score[]', 'value' => $array['score'], 'other' => " data-id='{$array['id']}' data-type='score'", 'blur' => 'setText', 'class' => 'textPrice'));
                        break;
                    case "list":
                        $row[] = text(array('name' => 'list[]', 'value' => $array['list'], 'other' => " data-id='{$array['id']}' data-type='list'", 'blur' => 'setText', 'class' => 'textPrice'));
                        break;
                    case "rate":
                        $row[] = $rate;
                        break;
                    case "seeText":
                        $row[] = $seeText;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        $json['html'] = $page['hint'] . $button . "<form name='topicForm'>" . $li . "</form>" . $page['button'];
        $json['html'] .= <<<eof
<style>
.left-progress,.right-progress{
 display: inline-block;
 height: 100%;
}
.left-progress{
 background-color: #629afd
}
.right-progress{
 background-color: red;
}
</style>
<script>
         function setText(obj){
         let id = $(obj).data('id');
         let type = $(obj).data('type');
            let val = $(obj).val()
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=setText',{id:id,type:type, text:val},function(res) {
                if(res.warn !== 1){
                   warn(res.warn)
                }
            },'json')
    }
</script>

eof;

        return json_encode($json, 320);
    }


    /**
     * 填写分数和排序号
     * @return bool|string
     */
    public function setText()
    {
        $id = $this->post('id');
        $type = $this->post('type');
        $text = $this->post('text');
        $infoMx = query(self::tableMx, " id = '$id' ");
        $info = query(self::table, " id = '{$infoMx['orderId']}' ");
        if (!$infoMx['id']) {
            $json['warn'] = L('topic.table.find_none_test');
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = L('topic.table.not_draft');
        } elseif (empty($type) || !in_array($type, ['list', 'score'])) {
            $json['warn'] = L('topic.table.changeType');
        } elseif (empty($text)) {
            $json['warn'] = L('topic.table.no_data');
        } elseif ($type == 'list' && static::total(array('table' => self::tableMx, 'where' => " and orderId = '$infoMx[orderId]' and id !='$id' and list = '$text'")) > 0) {
            $json['warn'] = L('topic.table.repeatList');
        } else {
            $json['warn'] = update([
                'table' => self::tableMx,
                'field' => [
                    $type => $text,
                    'updateTime' => $this->time,
                ],
                'where' => " id = '$id' "
            ]);
            if ($json['warn'] == '更新成功') {
                $json['warn'] = 1;
            }
        }
        return json_encode($json, 320);
    }

    /**
     *
     * @return bool|string
     */
    public function addMx()
    {
        $html =
            select(array("name" => "type", "title" => L('topic.table.topicType'), "option" => explode('，', para('topicLibraryOption')))) .
            text(array("name" => "aimType", "title" => L('topic.table.topicName'))) .
            select(array("name" => "topicType", 'option' => $this->typeOption, "title" => L('topic.table.questionsType'))) .
            text(array("name" => "title", "title" => L('topic.table.stem'))) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"subForm('mxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addMxEdit');\" type='button' class='searchSub' value='" . L('recruitment.table.commit') . "'>";
        $html = $this->search($html);
        return $this->layer(array("title" => L('topic.table.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *添加题目
     */
    public function addMxSearch()
    {
        $id = $this->post('id');
        $where = " 1=1 and b.id not in (select topicLibraryMxId from " . self::tableMx . " where  orderId = '$id')";
        $and = '';
        $like = [
            'a.name' => $this->post('aimType'),
            'b.title' => $this->post('title'),
            'b.topicType' => $this->post('topicType'),
        ];
        $equal = [
            'a.state' => '启用',
            'b.state' => '启用',
            'a.type' => $this->post('type'),
        ];
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            'field' => "a.name,b.id,a.type,b.topicType,b.title",
            "table" => "topic_library as a join topic_library_detail as b on a.id = b.orderId",
            "where" => $where,
            'pageNum' => 50,
            "order" => " b.`time` ASC",
        ]);

        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[] = [$checkAll, L('topic.table.topicType'), L('topic.table.topicName'), L('topic.table.questionsType'), L('topic.table.stem')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['id']),
            );
            $tr[] = array(
                $this->dominate($dominate),
                $array['type'],
                $array['name'],
                $array['topicType'],
                $array['title'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
            hidden(array('name' => 'id', 'value' => $id)) .
            $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $info = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('topic.table.paper_edit_permission');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('topic.table.chooseTopic');
        } elseif ($info['state'] == '已发布') {
            $json['warn'] = L('topic.table.not_draft');
        } else {
            $x = 0;
            //获取最后一题的题号
            $last = query(self::tableMx, " orderId = '$id' order by list desc");
            $list = intval($last['list']) + 1;
            foreach ($mxIdArr as $mxId) {
                $mx = query(self::tableMx, " topicLibraryMxId = '$mxId' and orderId = '$id'");
                if (!$mx['id']) {
                    $topic = query('topic_library_detail', " id = '$mxId'");
                    $warn = insert(array(
                        'table' => self::tableMx,
                        'field' => [
                            'id' => suiji(),
                            'orderId' => $id,
                            'topicLibraryId' => $topic['orderId'],
                            'topicLibraryMxId' => $mxId,
                            'score' => $topic['score'] > 0 ? $topic['score'] : 1,
                            'list' => $list,
                            'time' => $this->time
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $list++;
                        $x++;
                        $text = str_replace(['{{staffName}}', '{{id}}', '{{name}}'], [$this->control['name'], $mxId, $info['name']], L('topic.table.add_text'));
                        $this->logText(array("type" => self::page, "text" => $text));
                    }
                }
            }
            if ($info['isRandom'] == '是') {
                //随机排序题号
                $this->randomTopic($info['id']);
            }
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . $this->get('cla') . "&fun=detail&menu=topic&id=" . $info['id'];
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('topic.table.add_warn'));
        }
        return json_encode($json, 320);
    }

    /**
     * 随机排列题目
     * @param $id
     */
    public function randomTopic($id)
    {
        $result = find(array('table' => self::tableMx, 'where' => " orderId = '$id' order by list asc,time"));
        if (is_array($result['array'])) {
            shuffle($result['array']);//随机排列数组
            foreach ($result['array'] as $k => $array) {
                update(array('table' => self::tableMx, 'field' => ['list' => $k + 1], 'where' => " id = '$array[id]'"));
            }
        }
    }

    /*列表页-查询条件*/
    public function scoreOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('staffProfiles.table.name') => text(array("name" => "name")),
                    L('staffProfiles.table.department')   => selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'class' => 'width200']),
                    L('topic.table.endTime') => text(array("name" => "createTime", 'laydate' => ['type' => 'datetime', 'range' => '~'])),
                ],
                [
                    L('trainingPlan.table.state')  => select(array("name" => "state", "option" => ['合格', '不合格'])).
                        hidden(array('name' => 'id', 'value' => $this->get('id'))),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 成绩
     */
    public function score()
    {
        $html = $this->scoreOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','addPeople',{id:'" . $this->get('id') . "'})\" class='spanButton'>" . L('topic.table.chooseStaff') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {act:'delPeople',id:'" . $this->get('id') . "'})\">" . L('topic.table.del') . "</span>\n";
        }
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function scoreSearch()
    {
        $id = $this->post('id');
        $paper = query(self::table, "id = '$id'");
        $where = " and a.orderId = '$id'";
        $and = '';
        $like = [
            'b.name' => $this->post('name'),
        ];
        $equal = [
            'b.state' => $this->post('state'),
        ];
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and b.jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
        }
        if ($this->post('createTime')) {
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and b.startTime >='{$timeArr[0]}' and b.startTime <='{$timeArr[1]}'";
        }
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'a.list asc,a.`time`',
            "sort"   => $this->post('list_sort') ?: "asc",
            "array"  => array(),
        ));
        $page = $this->page([
            'field' => "a.*,b.startTime,b.commitTime,b.score,b.state,b.id as recordId,b.isRead",
            "table" => "paper_people as a left join topic_answer_record as b on (a.orderId = b.paperId and a.stid = b.stid)",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array($this->checkAll("peopleForm", "peopleId"));
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "peopleId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "staff":
                        $staff = query('staff', " stid = '$array[stid]'");
                        $row[] = $staff['name'];
                        break;
                    case "department":
                        $job = query('job', " id = '$array[jobId]'");
                        $department = query('department', " id = '$job[departmentId]'");
                        $row[] = $department['name'];
                        break;
                    case "second":
                        $second = strtotime($array['commitTime']) - strtotime($array['startTime']);
                        $second = $second > 0 ? $second : 0;
                        $row[] = $second;
                        break;
                    case "mx":
                        $mx = '';
                        if ($array['recordId']) {
                            $mx = "<span class='del-row-button' onclick=\"window.open('" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=previewPaper&method=record&stid={$array['stid']}&id={$array['orderId']}')\">" . L('topic.table.answerInfo') . "</span>";
                            if (($paper['type'] == '考试' && !$array['isRead']) || $paper['type'] == '练习') {
                                $mx .= "&emsp;<span class='del-row-button' onclick=\"window.open('" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=previewPaper&reading=reading&method=record&stid={$array['stid']}&id={$array['orderId']}')\">" . L('topic.table.markPaper') . "</span>";
                            }
                        }
                        $row[] = $mx;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
        $json['html'] = $page['hint'] . $button . "<form name='peopleForm'>" .$li . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     *添加人员
     * @return bool|string
     */
    public function addPeople()
    {
        $html =
            text(array("name" => "name", "title" => L('staffProfiles.table.name'))) .
            selectMultiple(array("name" => "jobId", "title" => L('staffProfiles.table.job'), 'table' => 'job', 'sqlId' => 'id', 'sqlField' => 'name')) .
            hidden(array('name' => 'id', 'value' => $this->post('id')));
        $button = "<input style='margin-left: 5px' onclick=\"subForm('peopleMxForm', '" . root . "control/adIndex.html?cla=" . self::page . "&fun=addPeopleEdit');\" type='button' class='searchSub' value='" . L('recruitment.table.commit') . "'>";
        $html = $this->searchExecute(['html' => $html,'option'=>'{fixed:false}']);
        return $this->layer(array("title" =>  L('topic.table.add'), "height" => 600, "width" => 1000, "html" => $html, "button" => $button));
    }

    /**
     *选择员工
     */
    public function addPeopleSearch()
    {
        $id = $this->post('id');
        $where = " state in ('转正','试用','留职')  and stid not in (select stid from paper_people where  orderId = '$id')";
        $and = '';
        $like = [
            'name' => $this->post('name'),
        ];
        $equal = [
            'jobId' => $this->post('jobId'),
            'workFlow' => '已复核',
        ];
        $where .= search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "staff",
            "where" => $where,
            'pageNum' => 50,
            "order" => " `time` ASC",
        ]);
        //获取表头
        $checkAll = $this->checkAll("peopleMxForm", "mxId");
        $tr[] = [$checkAll, L('staffProfiles.table.department'), L('staffProfiles.table.job'), L('staffProfiles.table.name')];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate = array(
                "box" => array("name" => "mxId", "value" => $array['stid']),
            );
            $job = query('job', " id = '$array[jobId]'");
            $department = query('department', " id ='$job[departmentId]'");
            $tr[] = array(
                $this->dominate($dominate),
                $department['name'],
                $job['name'],
                $array['name'],
            );
        }
        $json['html'] = $page['hint'] .
            "<form name='peopleMxForm'>" .
                hidden(array('name' => 'id', 'value' => $id)) .
                $this->tableMany(array("tr" => $tr, "showSort" => true)) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     * 添加考试人员中
     * @return bool|string
     */
    public function addPeopleEdit()
    {
        $id = $this->post('id');
        $mxIdArr = $this->post('mxId');
        $info = query(self::table, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('topic.table.paper_edit_permission');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('topic.table.chooseStaff');
        } else {
            $x = 0;
            foreach ($mxIdArr as $mxId) {
                $mx = query('paper_people', " stid = '$mxId' and orderId = '$id'");
                if (!$mx['id']) {
                    $staff = query('staff', " stid = '$mxId'");
                    $warn = insert(array(
                        'table' => 'paper_people',
                        'field' => [
                            'id' => suiji(),
                            'orderId' => $id,
                            'stid' => $mxId,
                            'jobId' => $staff['jobId'],
                            'time' => $this->time
                        ]
                    ));
                    if ($warn == '新增成功') {
                        $x++;
                        $text = str_replace(['{{staffName}}', '{{name}}', '{{paperName}}'], [$this->control['name'], $staff['name'], $info['name']], L('topic.table.add_staff_text'));
                        $this->logText(array("type" => self::page, "text" => $text));
                    }
                }
            }
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . $this->get('cla') . "&fun=detail&menu=score&id=" . $info['id'];
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('topic.table.add_staff_warn'));
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd =$word= false; // 需要密码
        switch ($act) {
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此考卷，撤回后将会删除已生成的考试记录，请谨慎操作？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'delPeople':
                $act = 'del';
                $msg = L('topic.table.delStaff');
                $title = self::page . 'DeletePeople';
                $function = 'deletePeople';
                $form = self::page . 'OperateForm, peopleForm';
                $power = '';
                break;
            case 'delTopic':
                $act = 'del';
                $msg = L('topic.table.delTopic');
                $title = self::page . 'DeleteTopic';
                $function = 'deleteTopic';
                $form = self::page . 'OperateForm, topicForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = L('topic.table.delPaper');
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('jon.other.permission_warn'));
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word'=>$word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除考试人员
     * @return bool|string
     */
    public function deletePeople()
    {
        $array = $this->post('peopleId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query('paper_people', " id = '$id' ");
                $record = query('topic_answer_record', " paperId = '$mx[orderId]' and stid = '$mx[stid]'");
                $staff = query('staff', " stid = '$mx[stid]'");
                if (!empty($record['id'])) {
                    //返回
                    $warn = L('topic.table.people_del_error');
                } else {
                    delete(array("table" => 'paper_people', "where" => " id = '$id' "));
                    //返回
                    $warn = L('job.other.delete_success');
                    $x++;
                }
                $text .= str_replace(['{{id}}', '{{name}}'], [$mx['orderId'], $staff['name']], L('topic.table.people_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('topic.table.people_del_log')) . "<br>" . $text;

            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('topic.table.people_del_warn'));

            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . $this->get('cla') . "&fun=detail&menu=score&id=" . $mx['orderId'];
        }
        return json_encode($json, 320);
    }

    /**
     * 删除试题
     * @return bool|string
     */
    public function deleteTopic()
    {
        $array = $this->post('topicId');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $mx = query(self::tableMx, " id = '$id' ");
                $info = query(self::table, " id = '$mx[orderId]'");
                if ($info['state'] == '已发布') {
                    $warn = L('topic.table.paper_del_error');
                } else {
                    delete(array("table" => self::tableMx, "where" => " id = '$id' "));
                    //返回
                    $warn = L('job.other.delete_success');
                    $x++;
                }

                $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $mx['topicLibraryMxId']], L('topic.table.paper_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('topic.table.paper_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('topic.table.paper_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . 'control/adIndex.html?cla=' . $this->get('cla') . "&fun=detail&menu=topic&id=" . $mx['orderId'];
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('staffProfiles.tip.permission_del_warn');
        } elseif (empty($array)) {
            $json['warn'] = L('staffProfiles.tip.no_data_choose');
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已发布') {
                    $warn =L('topic.table.paper_del_error');
                } else {
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'paper_people', "where" => " orderId = '$id' "));
                    //返回
                    $warn = L('job.other.delete_success');
                    $x++;
                }
                $text .= str_replace(['{{name}}', '{{id}}'], [$info['name'], $info['id']], L('topic.table.p_del_text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('topic.table.p_del_log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('topic.table.p_del_warn'));
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 计算正确和错误人数
     * @param $paperId
     * @param $topicId
     * @return array
     */
    public function calculateRate($paperId, $topicId): array
    {
        //答题记录
        $result = find(array('table' => 'topic_answer_record_detail as a join topic_answer_record as b on a.orderId = b.id', 'field' => "a.*", 'where' => " b.isCommit = 1 and a.paperId = '$paperId' and a.topicLibraryMxId = '$topicId'"));
        $rightPeople = $wrongPeople = $totalNum = 0;
        $rightPeopleText = $wrongPeopleText = '';
        foreach ($result['array'] as $array) {
            $totalNum++;
            $staff = query('staff', "stid = '$array[stid]'");
            if ($array['state'] == 1) {
                $rightPeople++;
                $rightPeopleText .= $staff['name'] . '，';
            } else {
                $wrongPeople++;
                $wrongPeopleText .= $staff['name'] . '，';
            }
        }
        $rightPeopleText = $rightPeopleText ?: '--';
        $wrongPeopleText = $wrongPeopleText ?: '--';
        return ['rightNum' => $rightPeople, 'wrongNum' => $wrongPeople, 'totalNum' => $totalNum, 'rightPeopleText' => $rightPeopleText, 'wrongPeopleText' => $wrongPeopleText];
    }

    /**
     * 查看答题人数
     */
    public function seePaperRecord(): string
    {
        $paper = query(self::table, " id = '{$this->get('id')}'");
        //试题信息
        $topic = query('topic_library_detail', " id = '{$this->get('topicId')}'");

        $choiceText = '';
        $choiceArr = json_decode($topic['item'], true);//选项
        $answerArr = json_decode($topic['answer'], true);//答案
        if ($topic['topicType'] == '多选题') {
            foreach ($choiceArr as $i => $choice) {
                $checked = '';
                if (in_array($i, $answerArr)) {
                    $checked = 'checked';
                }

                $choiceText .= '<li><label class="radioLabel"><input type="checkbox" ' . $checked . ' value="' . $i . '" name="reply[]">&nbsp;' . $this->itemWord[$i] . '. ' . $choice . '</label></li>';
            }
        } else {
            foreach ($choiceArr as $i => $choice) {
                $checked = '';
                if (in_array($i, $answerArr)) {
                    $checked = 'checked';
                }
                $choiceText .= '<li><label class="radioLabel"><input name="reply" ' . $checked . ' value="' . $i . '" type="radio">&nbsp;' . $this->itemWord[$i] . '. ' . $choice . '</label></li>';
            }
        }
        $result = $this->calculateRate($paper['id'], $topic['id']);
        $rightPeople = str_replace(['{{num}}'],[$result['rightNum']],L('topic.table.rightPeople'));
        $wrongPeople = str_replace(['{{num}}'],[$result['wrongNum']],L('topic.table.wrongPeople'));
        $html = <<<efo
                            <div class="paper">
                            <div class="paper-title-block">
                            <span class="paper-title-text">{$paper['name']}</span>
                            </div>
                            <div class="paper-content-block">
                            <form name="topicForm">
                            <div class="topic-block">
                                        <div class="topic-title">
                                        {$topic['title']}【{$topic['topicType']}】
                                        </div>
                                        <div class="topic-item">
                                        <ul>
                                        {$choiceText}
                                        </ul>
                                        </div>
                                        <div style="margin-top: 20px">
                                        <div style="margin-top: 10px">{$rightPeople}：{$result['rightPeopleText']}</div>
                                        <div style="margin-top: 10px">{$wrongPeople}：{$result['wrongPeopleText']}</div>
</div>
                                        </div>
                            </form>
                            </div>
                            </div>

efo;


        return $this->header() . $this->style() . $html . warn() . $this->footer();
    }

    /**
     *试卷预览
     */
    public function previewPaper(): string
    {
        $stid = $this->control['stid'];
        $paper = query(self::table, " id = '{$this->get('id')}'");
        $method = $this->get('method');
        $reading = $this->get('reading');
        if (empty($paper['id'])) {
            $warn = L('topic.table.no_paper');
            goto resp;
        } elseif (time() >= strtotime($paper['endTime']) && $method == 'answer') {
            $warn =L('topic.table.answerTime');
            goto resp;
        } else {
            $result = find(array('table' => self::tableMx, 'where' => " orderId = '$paper[id]' order by list asc,time asc"));

            $topicItemText = '';
            $displayNone = '';
            //试卷答题记录
            $topicAnswerRecord = query('topic_answer_record', " paperId = '$paper[id]' and stid = '$stid'");
            if ($method === 'answer') {
                if (empty($topicAnswerRecord['id'])) {
                    //总分
                    $score = find(array('table' => self::tableMx, "where" => " orderId = '$paper[id]'", 'sum' => "score"));
                    insert(array(
                        'table' => 'topic_answer_record',
                        'field' => [
                            'id' => self::getId(),
                            'paperId' => $paper['id'],
                            'stid' => $stid,
                            'startTime' => $this->time,
                            'jobId' => $this->control['jobId'],
                            'name' => $this->control['name'],
                            'totalScore' => $score,
                            'score' => 0,
                            'time' => $this->time
                        ]
                    ));
                    $endTime = date('Y-m-d H:i:s', time() + $paper['minute'] * 60);//交卷时间
                } else {
                    $endTime = date('Y-m-d H:i:s', strtotime($topicAnswerRecord['startTime']) + $paper['minute'] * 60);//交卷时间
                }
            } else {
                $displayNone = "display:none";
                $endTime = '0000-00-00 00:00:00';
            }
            if ($paper['answerType'] == '逐题答题' && $method != 'record') {
                $maxList = count($result['array']);
                if (empty($this->get('list')) || $this->get('list') <= 0 || !is_numeric($this->get('list'))) {
                    $list = 1;
                } else {
                    $list = $this->get('list') > $maxList ? $maxList : $this->get('list');
                }
                $topic['id'] = '';
                $topicTip = str_replace(['{{list}}','{{maxList}}'],[$list,$maxList],L('topic.table.paperBage'));

                foreach ($result['array'] as $array) {
                    if ($array['list'] >= $list) {
                        //试题信息
                        $topic = query('topic_library_detail', " id = '$array[topicLibraryMxId]'");
                        //答题记录
                        $record = query('topic_answer_record_detail', " stid = '$stid' and paperId = '$paper[id]' and topicLibraryMxId = '$topic[id]'");
                        $choiceText = '';
                        $choiceArr = (array)json_decode($topic['item'], true);//选项

                        switch ($topic['topicType']) {
                            case '多选题':
                                foreach ($choiceArr as $i => $choice) {
                                    $reply = json_decode($record['reply'], true);
                                    $checked = '';
                                    if (is_array($reply)) {
                                        if (in_array($i, $reply) && $method == 'answer') {
                                            $checked = 'checked';
                                        }
                                    }

                                    $choiceText .= '<li><label class="radioLabel"><input type="checkbox" ' . $checked . ' value="' . $i . '" name="reply[]">&nbsp;' . $this->itemWord[$i] . '. ' . $choice . '</label></li>';
                                }
                                break;
                            case '主观题':
                                $choiceText .= '<li><textarea class="text-area" name="reply[' . $topic['id'] . ']"></textarea></li>';
                                break;
                            default:
                                foreach ($choiceArr as $i => $choice) {
                                    $reply = json_decode($record['reply'], true);
                                    $checked = '';
                                    if (is_array($reply)) {
                                        if (in_array($i, $reply) && $method == 'answer') {
                                            $checked = 'checked';
                                        }
                                    }
                                    $choiceText .= '<li><label class="radioLabel"><input name="reply" ' . $checked . ' value="' . $i . '" type="radio">&nbsp;' . $this->itemWord[$i] . '. ' . $choice . '</label></li>';
                                }
                                break;
                        }

                        $topic['title'] = html_entity_decode($topic['title'], ENT_QUOTES);
                        $topicItemText .= <<<efo
                                        <div class="topic-block">
                                        <div class="topic-title">
                                        {$list}、{$topic['title']}【{$topic['topicType']}】
                                        </div>
                                        <div class="topic-item">
                                        <ul>
                                        {$choiceText}
                                        </ul>
                                        </div>
                                        </div>
efo;
                        break;
                    }
                }
                $commitPaperBtn = L('topic.table.commitPaper');
                $remindTime = L('topic.table.remindTime');
                $nextTopic = L('topic.table.nextTopic');
                $preTopic = L('topic.table.preTopic');
                $closed = L('topic.table.closed');
                $seeTopicInfo = L('topic.table.seeTopicInfo');
                $shortcut = L('topic.table.shortcut');
                $commitSuc = L('topic.table.commitSuc');
                $html = <<<efo
                            <div class="paper" style="position: relative;">
                            <div class="paper-title-block">
                            <span class="paper-title-text">{$paper['name']}</span>

                            <div class="paper-commit-button li-btn-blue-bg" style="{$displayNone}" onclick="commitPaper()">{$commitPaperBtn}</div>
                            <input name="endTime" type="hidden" value="{$endTime}">
                            <span class="papaer-title-time" style="$displayNone">{$remindTime}：<span class="papaer-title-time-text">00:00:00</span></span>
                            </div>
                            <div class="paper-content-block">
                            <form name="topicForm">
                            {$topicItemText}
                            <input name="topicId" value="{$topic['id']}" type="hidden">
                            </form>
                            </div>
                            <div class="footer">
                            <div class="footer-left">{$topicTip}</div>
                             <div class="footer-center"><span class="spanButton button-text" data-type="pre"  onclick="locationTo('pre')">< $preTopic</span><span class="spanButton button-text" data-type="next" onclick="locationTo('next')">$nextTopic ></span></div>
                              <div class="footer-right">$shortcut</div>
                             </div>
<div id='mask-layer' style='display: none; width: 210mm;height: auto;background-color: white;position: fixed;top: 0'>
                                    <div style="margin: 40% auto;width: 300px;text-align: center">
                                    <div style="text-align: center">
                                        <svg t="1635476976401" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2654" width="64" height="64"><path d="M512 1024A512 512 0 1 1 512 0a512 512 0 0 1 0 1024z m-49.590857-377.197714L315.977143 498.614857 219.428571 590.848c70.217143 37.814857 168.594286 106.788571 252.854858 213.723429C531.821714 692.662857 715.337143 463.725714 804.571429 443.245714c-14.409143-57.709714-22.528-166.034286 0-223.817143-183.003429 120.685714-342.162286 427.373714-342.162286 427.373715z" p-id="2655" fill="#629AFE"></path></svg>
                                        <div style="margin-top: 10px;font-size: 20px">$commitSuc</div>
                                    </div>
                                    <div style="cursor: pointer;width: 100%;color: white;height: 40px;text-align: center;margin-top: 20px;line-height: 40px;border-radius:2px;background-color: #4C9CFB" id="seeDetail">$seeTopicInfo</div>
                                    <div style="cursor: pointer;width: 100%;text-align: center;height: 40px;line-height: 40px;margin-top: 20px;border-radius:2px;background-color: #e6e6e6" id="seeClose">$closed</div>
</div>
                                </div>
                            </div>
<style>

.paper{
          width: 210mm;
          height: auto;
          background-color: #fff;
          margin: 0 auto;
          overflow: auto
        }
</style>
<script>



        $(document).keydown(function (e) {
            if (e.keyCode == 37)
            {
                //上一题
             locationTo('pre')
            }else if(e.keyCode == 39){
                //下一题
                locationTo('next')
            }
        });
 /***题目跳转******/
 function locationTo(type){
     let id = GetQueryString('id');
     let list = GetQueryString('list');
      let method = GetQueryString('method');
     let formData = new FormData($("[name='topicForm']")[0]);
     formData.append('paperId', id);
     formData.append('list', list);
     formData.append('type', type);
      formData.append('method', method);
       $.ajax({
            url: '{$this->root}control/adIndex.html?cla={$this->get('cla')}&fun=showNextTopic',
            type: 'POST',
            cache: false,
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            // beforeSend: function () {
            //     console.log("正在进行，请稍候");
            // },
            success: function (res) {
                let data = JSON.parse(res);
                if (data.warn==2){
                    location.href = data.href;
                }else{
                    warn(data.warn);
                }

            },
            error: function (responseStr) {
                console.log(responseStr);
            }
        });

 }
 function commitPaper(){
      let id = GetQueryString('id');
     let list = GetQueryString('list');
    let method = GetQueryString('method');
     let formData = new FormData($("[name='topicForm']")[0]);
     formData.append('paperId', id);
     formData.append('list', list);
     formData.append('type', '');
     formData.append('method', method);
     $.ajax({
            url: '{$this->root}control/adIndex.html?cla={$this->get('cla')}&fun=commitPaper',
            type: 'POST',
            cache: false,
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            // beforeSend: function () {
            //     console.log("正在进行，请稍候");
            // },
            success: function (res) {
                let data = JSON.parse(res);
                if (data.warn==2){
                     closeWindow();
                     clearTimeout(timeClicker);

                }else{
                    warn(data.warn);
                }

            },
            error: function (responseStr) {
                console.log(responseStr);
            }
        });
 }

</script>
efo;
            } else {
                $recordDiv = $readingButton = "";
                $paperStid = L('topic.table.paperStid');
                $scoreTitle = L('topic.table.scoreTitle');
                $commitTime = L('recruitment.table.commitTime');

                if ($method == 'record') {
                    $stid = $this->get('stid');
                    if ($topicAnswerRecord['isCommit'] && $topicAnswerRecord['isRead']) {
                        //已提交试卷
                        $staff = query('staff', "stid = '$stid'");
                        $second = strtotime($topicAnswerRecord['commitTime']) - strtotime($topicAnswerRecord['startTime']);
                        $secondText = str_replace(['{{second}}'],[$second],L('topic.table.second'));
                        $recordDiv = <<<efo
<div class="topic-block"><span>{$paperStid}：{$staff['name']}</span><span class="dis-left-margin">{$commitTime}：{$topicAnswerRecord['commitTime']}</span><span class="dis-left-margin">$secondText</span>
<span class="dis-left-margin">{$scoreTitle}：{$topicAnswerRecord['score']}/{$topicAnswerRecord['totalScore']}</span><span class="dis-left-margin">{$topicAnswerRecord['state']}</span></div>

efo;
                    }
                    if ($reading === 'reading') {
                        $readingButton = '<div class="paper-commit-button li-btn-blue-bg" onclick="confirmReading()">'.L('topic.table.confirm').'</div>';
                    }
                }
                //整卷答题
                foreach ($result['array'] as $k => $array) {
                    $topicScore = '';
                    $list = $k + 1;
                    $topic = query('topic_library_detail', " id = '$array[topicLibraryMxId]'");
                    $choiceText = '';
                    $choiceArr = (array)json_decode($topic['item'], true);//选项
                    $answerArr = (array)json_decode($topic['answer'], true);//答案

                    //对错标识
                    $answerSign = $topic_item_left = $topic_title_left = '';
                    //答题记录
                    $record = query('topic_answer_record_detail', " stid = '$stid' and paperId = '$paper[id]' and topicLibraryMxId = '$topic[id]'");
                    if ($method == 'record') {
                        //判断当前答题正确或错误
                        if ($record['state'] == 1) {
                            $answerSign = "<span class='topic-right'></span>";
                        } else {
                            $answerSign = "<span class='topic-wrong'></span>";
                        }
                        $answerSign = $topic['topicType'] === '主观题' ? '' : $answerSign;
                        $topic_item_left = "topic-item-left";
                        $topic_title_left = "topic-title-left";
                    }
                    $main_score_input = $answerText = '';
                    $answerWord = L('topic.table.answer');
                    switch ($topic['topicType']) {
                        case '多选题':
                            foreach ($choiceArr as $i => $choice) {
                                $checked = $answerText = '';
                                if ($method == 'record') {
                                    //查看答题记录
                                    $reply = (array)json_decode($record['reply'], true);
                                    if (is_array($reply)) {
                                        if (in_array($i, $reply)) {
                                            $checked = 'checked';
                                        }
                                    }
                                    if (in_array($i, $answerArr)) {
                                        $answerText = "<span style='color: #00B83F'>[$answerWord]</span>";
                                    }
                                }
                                $choiceText .= '<li><label class="radioLabel"><input ' . $checked . ' type="checkbox" value="' . $i . '" name="reply[' . $topic['id'] . '][]">&nbsp;' . $this->itemWord[$i] . '. ' . $choice . '</label>' . $answerText . '</li>';
                            }
                            break;
                        case '主观题':
                            if ($method == 'record') {
                                $referenceAnswer = L('topic.table.referenceAnswer');
                                //查看答题记录
                                $record['reply'] =  preg_replace('/\r|\n/','\n',trim($record['reply']));
                                $reply = (array)json_decode($record['reply'], true);
                                $paper_library_detail = query('paper_library_detail', "orderId = '$paper[id]' and topicLibraryMxId = '$topic[id]'");
                                $answerText = "<p>{$referenceAnswer}：" . ($answerArr[0] ?? '') . "</p>";
                                $getScore = L('topic.table.getScore');
                                if ($reading === 'reading') {

                                    $main_score_input = "<span style='white-space: nowrap'>{$getScore}：<input style='width: 70px' type='number' name='score[$topic[id]]' value=''></span>";
                                } else {
                                    $main_score_input = "{$getScore}：" . $record['score'];
                                }
                                $paper_library_detail['score'] = $paper_library_detail['score'] == (int)$paper_library_detail['score'] ? (int)$paper_library_detail['score'] : $paper_library_detail['score'];
                                $topicScore = "（{$paper_library_detail['score']}分）";
                            }
                            $choiceText .= '<li><textarea class="text-area" name="reply[' . $topic['id'] . ']">' . ($reply[0] ?? '') . '</textarea>' . $answerText . '</li>';
                            break;
                        default:
                            foreach ($choiceArr as $i => $choice) {
                                $checked = $answerText = '';
                                if ($method == 'record') {
                                    //查看答题记录
                                    $reply = json_decode($record['reply'], true);

                                    if (is_array($reply) && !empty($reply)) {
                                        if (in_array($i, $reply)) {
                                            $checked = 'checked';
                                        }
                                    }
                                    if (in_array($i, $answerArr)) {
                                        $answerText = "<span style='color: #00B83F'>[$answerWord]</span>";
                                    }
                                }
                                $choiceText .= '<li><label class="radioLabel"><input ' . $checked . ' value="' . $i . '" name="reply[' . $topic['id'] . ']" type="radio">&nbsp;' . $this->itemWord[$i] . '. ' . $choice . '</label>' . $answerText . '</li>';
                            }
                            break;
                    }
                    $topic['title'] = html_entity_decode($topic['title'], ENT_QUOTES);
                    $topicItemText .= <<<efo
                                        <div class="topic-block">
                                        {$answerSign}
                                        <div class="topic-title {$topic_title_left}">
                                        {$list}、{$topic['title']}{$topicScore}【{$topic['topicType']}】<span style="margin-left: 50px">{$main_score_input}</span>
                                        </div>
                                        <div class="topic-item {$topic_item_left}">
                                        <ul>
                                        {$choiceText}
                                        </ul>
                                        </div>
                                        </div>
efo;
                }
                $remindTime = L('topic.table.remindTime');
                $commitPaperBtn = L('topic.table.commitPaper');
                $seeTopicInfo = L('topic.table.commitPaper');
                $closed = L('topic.table.closed');
                $commitSuc = L('topic.table.commitSuc');
                $html = <<<efo
                            <div class="paper" style="position: relative">
                            <div class="paper-title-block">
                            <span class="paper-title-text">{$paper['name']}</span>
                             <div class="paper-commit-button li-btn-blue-bg" style="{$displayNone}" onclick="commitPaper()">$commitPaperBtn</div>
                             {$readingButton}
                            <input name="endTime" type="hidden" value="{$endTime}">
                            <span class="papaer-title-time" style="$displayNone">{$remindTime}：<span class="papaer-title-time-text">00:00:00</span></span>
                            </div>
                            <div class="paper-content-block">
                            {$recordDiv}
                            <form name="topicForm">
                            {$topicItemText}
                            </form>
                            </div>
                                <div id='mask-layer' style='display: none;width: 210mm;height: 100%;background-color: white;position: fixed;top: 0'>
                                    <div style="margin: 40% auto;width: 300px;text-align: center">
                                    <div style="text-align: center">
                                        <svg t="1635476976401" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2654" width="64" height="64"><path d="M512 1024A512 512 0 1 1 512 0a512 512 0 0 1 0 1024z m-49.590857-377.197714L315.977143 498.614857 219.428571 590.848c70.217143 37.814857 168.594286 106.788571 252.854858 213.723429C531.821714 692.662857 715.337143 463.725714 804.571429 443.245714c-14.409143-57.709714-22.528-166.034286 0-223.817143-183.003429 120.685714-342.162286 427.373714-342.162286 427.373715z" p-id="2655" fill="#629AFE"></path></svg>
                                        <div style="margin-top: 10px;font-size: 20px">$commitSuc</div>
                                    </div>
                                    <div style="cursor: pointer;width: 100%;color: white;height: 40px;text-align: center;margin-top: 20px;line-height: 40px;border-radius:2px;background-color: #4C9CFB" id="seeDetail">$seeTopicInfo</div>
                                    <div style="cursor: pointer;width: 100%;text-align: center;height: 40px;line-height: 40px;margin-top: 20px;border-radius:2px;background-color: #e6e6e6" id="seeClose">$closed</div>
</div>
                                </div>
                            </div>

<script>
function commitPaper(){
     let id = GetQueryString('id');
     let method = GetQueryString('method');
     let formData = new FormData($("[name='topicForm']")[0]);
     formData.append('paperId', id);
     formData.append('method', method);
     $.ajax({
            url: '{$this->root}control/adIndex.html?cla={$this->get('cla')}&fun=commitAllPaper',
            type: 'POST',
            cache: false,
            data: formData,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            // beforeSend: function () {
            //     console.log("正在进行，请稍候");
            // },
            success: function (res) {
                let data = JSON.parse(res);

                if (data.warn==2){
                     closeWindow();
                    clearTimeout(timeClicker);
                }else{
                    warn(data.warn);
                }
            },
            error: function (responseStr) {
                console.log(responseStr);
            }
        });
 }
</script>
efo;
            }
            return $this->header() . $this->style() . $html . warn() . $this->footer();
        }
        resp:
        $_SESSION['warn'] = $warn;
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }

    /**
     * 打印样式
     * @return string
     */
    public function style(): string
    {
        return <<<eof
        <style>
        .text-area{width: 100%;height: 100px}
        .paper-title-block{z-index: 100;}
        .topic-title-left{display: inline-block;margin-left: 10px}
        .topic-item-left{margin-left: 25px}
        .topic-right {width:7px;height: 13px;display: inline-block;border-bottom: 3px solid #00B83F;border-right: 2px solid #00B83F;-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);transform: rotate(45deg);vertical-align: top;}
        .topic-wrong {position: relative;display: inline-block;width: 13px;height: 13px;vertical-align: top;margin-top: 5px;}
        .topic-wrong::before,.topic-wrong::after {position: absolute;content: ' ';background-color: red;left: 5px;width: 2px;height: 13px;}
        .topic-wrong::before {transform: rotate(45deg);}
        .topic-wrong::after {transform: rotate(-45deg);}
        body{background-color: #AAAAAA;}
        .paper{width: 210mm;height: 100%;background-color: #fff; margin: 0 auto;overflow: auto}
        .paper-title-block{background-color: #fff;position: fixed;height: 55px;width: 210mm;line-height: 55px;box-shadow: 1px 1px 1px #e6e6e6;border-bottom: 1px solid #e6e6e6}
        .paper-title-text{font-size: 25px;margin-left: 40px;font-weight: bold}
        .paper-content-block{margin-top: 80px;padding-bottom: 50px}
        .topic-item ul li {margin-top: 10px;}
        .topic-block{margin: 25px 0 0 40px;}
        .topic-block .topic-title{font-size: 15px;font-weight: bold;width: 95%;}
        .topic-item{width: 95%}
        .footer{width: 90%;height: 80px;line-height: 80px;border-top: 1px solid #e6e6e6;margin: 0 auto;}
        .footer-left,.footer-right{width: 33%;display: inline-block;}
        .footer-center{width: 30%;display: inline-block;text-align: center}
        .footer-right{text-align: right;}
        .button-text{padding: 5px 3px;color: cornflowerblue;background-color: #e6e6e6;border: none}
        .papaer-title-time{float: right;margin-right: 20px}
        .paper-commit-button{float: right;width: 72px;height: 26px;margin-top: 15px;margin-right:50px;line-height: 24px;text-align: center;cursor: pointer;}
        .dis-left-margin{margin-left: 20px;}
        </style>\n
eof;
    }

    /**
     * 头部
     * @return string
     */
    public function header(): string
    {
        $root = root;
        $title = para('title');//网站标题
        return <<<eof
                <html lang="zh">
                <head>
                <title>{$title}</title>
                    <meta charset="UTF-8">
                    <link rel="stylesheet" type="text/css" href="{$root}static/stylesheet/css.css?v=4.2.710">
                    <link rel="icon" type="image/x-icon" href="{$root}favicon.ico?v=4.2.710">
                    <script type="text/javascript" src="{$root}static/javascript/jquery-1.11.2.min.js"></script>
                    <script type="text/javascript" src="{$root}static/javascript/js.js"></script>
                    <script type="text/javascript" src="{$root}static/javascript/lib.js"></script>
                </head>
                <body>
                <script>
                 var timeClicker = '';
                </script>
eof;
    }

    /**
     *尾部
     * @return string
     */
    public function footer(): string
    {
        $stid = self::$stid;
        $root = root;
        return <<<eof
            <script>
            function confirmReading(){
                 let id = GetQueryString('id');
                 let method = GetQueryString('method');
                 let formData = new FormData($("[name='topicForm']")[0]);
                 formData.append('paperId', id);
                 formData.append('method', method);
                 $.ajax({
                        url: '{$this->root}control/adIndex.html?cla={$this->get('cla')}&fun=confirmReading',
                        type: 'POST',
                        cache: false,
                        data: formData,
                        // 告诉jQuery不要去处理发送的数据
                        processData: false,
                        // 告诉jQuery不要去设置Content-Type请求头
                        contentType: false,
                        // beforeSend: function () {
                        //     console.log("正在进行，请稍候");
                        // },
                        success: function (res) {
                            let data = JSON.parse(res);
                            if (data.warn==2){
                                location.href = '{$this->root}control/adIndex.html?cla=paperManagement&fun=previewPaper&method=record&stid='+data.stid+'&id='+data.id
                            }else{
                                msg(data.warn,'error')
                            }
                        },
                        error: function (responseStr) {
                            console.log(responseStr);
                        }
                    });
                        }
                        //关闭当前标签页
                        function closeWindow(){
                            $(".paper").css('overflow','hidden');
                             $("#mask-layer").show();
            
                        }
                        $("#seeDetail").on('click',function() {
                            let id= GetQueryString('id');
                            location.href = '{$root}control/adIndex.html?cla=paperManagement&fun=previewPaper&method=record&stid={$stid}&id='+id;
                        });
                        $("#seeClose").on('click',function() {
                             let userAgent = navigator.userAgent;
                             if(userAgent.indexOf("Firefox")!==-1 || userAgent.indexOf("chrome")!== -1){
                                 location.href = "about:blank" ;
                              } else {
                                window.opener = null;
                                window.open('', '_self');
                                window.close();
                              }
                        });
                        $(function (){
            
                        function countTime() {
                             let method = GetQueryString('method');
                             if (method =='answer'){
                                 let endTime = $("[name='endTime']").val();
                                    var date = new Date();
                                    var nowTime = date.getTime();
                                    var endDate = new Date(endTime);//设置截止时间
                                    var end = endDate.getTime();
                                    var leftTime = end - nowTime; //时间差
                                    var d, h, m, s, ms;
                                        d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
                                        h = Math.floor(leftTime / 1000 / 60 / 60);
                                        m = Math.floor(leftTime / 1000 / 60 % 60);
                                        s = Math.floor(leftTime / 1000 % 60);
                                        ms = Math.floor(leftTime % 1000);
                                    if(leftTime >= 0) {
                                        if(ms < 100) { ms = "0" + ms;}
                                        if(s < 10) { s = "0" + s;}
                                        if(m < 10) { m = "0" + m;}
                                        if(h < 10) { h = "0" + h;}
                                    } else {
                                        commitPaper();
                                        clearTimeout(timeClicker);
                                        $(".papaer-title-time-text").css("color","red")
                                        $(".papaer-title-time-text").html("00:00:00")
                                        return;
                                    }
                                    //将倒计时赋值到div中
                                    $(".papaer-title-time-text").html(h + ':'+m + ":"+s)
                                    //递归每秒调用countTime方法，显示动态时间效果
                                    timeClicker = setTimeout(countTime, 50);
                             }
            
                        }
                        countTime();
            })
            </script>
            </body>
            </html>
eof;
    }

    /**
     * 添加阅读的分数
     */
    public function confirmReading(): bool|string
    {
        $stid = $this->control['stid'];//答题人
        $paperId = $this->post('paperId');//试卷ID
        $paper = query('paper_library', " id = '$paperId'");//试卷信息
        //开始答题记录
        $topicAnswerRecord = query('topic_answer_record', " paperId = '$paper[id]' and stid = '$stid'");
        if (empty($paper['id'])) {
            $json['warn'] = L('topic.table.no_paper');
        } elseif ($paper['state'] != '已发布') {
            $json['warn'] = L('topic.table.no_publish');
        } else {
            $tip = '';
            $this->startTrans();
            $scoreArr = $this->post('score');
            //此试卷所有题目
            $topicArr = find(array('table' => 'paper_library_detail', 'where' => " orderId = '$paper[id]' order by list asc"));
            foreach ($topicArr['array'] as $array) {
                $topic = query('topic_library_detail', "id = '$array[topicLibraryMxId]'");
                if ($topic['topicType'] == '主观题') {
                    $score = $scoreArr[$topic['id']] ?? 0;
                    if ($array['score'] < $score) {
                        $tip = L('topic.table.moreScore');
                        break;
                    } else {
                        //答题明细
                        $record = query('topic_answer_record_detail', " stid = '$stid' and paperId = '$paper[id]' and topicLibraryMxId = '$topic[id]'");
                        $warn = static::update(
                            array(
                                'table' => 'topic_answer_record_detail',
                                'field' => [
                                    'state' => $score > 0 ? 1 : 2,
                                    'score' => $score,
                                ],
                                'where' => " id = '$record[id]'"
                            )
                        );
                        if ($warn != '更新成功') {
                            $tip = L('topic.table.updateScore');
                            break;
                        }
                    }

                }
            }
            //计算得分
            $score = find(array('table' => 'topic_answer_record_detail', 'where' => " paperId = '$paperId' and stid = '$stid'", 'sum' => "score"));
            $json['warn'] = update(array(
                'table' => 'topic_answer_record',
                'field' => [
                    'score' => $score,
                    'state' => $score >= $paper['passMark'] ? '合格' : '不合格',
                    'isRead' => 1,
                ],
                'where' => " id = '$topicAnswerRecord[id]'"
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && empty($tip)) {
                $this->commitTrans();
                //添加日志
                $text = str_replace(['{{staffName}}','{{paperName}}','{{id}}'],[$this->control['name'],$paper['name'],$paper['id']],L('topic.table.paper_confirm'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn'] = 2;
                $json['stid'] = $stid;
                $json['id'] = $paperId;
            } else {
                $json['warn'] = $tip ?: $json['warn'];
                $this->rollback();
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 交卷是如果有未做的题目，则默认为错误答题
     */
    public function checkNoAnswerTopic($paper, $stid)
    {
        $topicArr = find(array('table' => 'paper_library_detail', 'where' => " orderId = '$paper[id]' order by list asc"));
        foreach ($topicArr['array'] as $array) {
            $record = query('topic_answer_record_detail', " paperId = '$paper[id]' and topicLibraryMxId = '$array[topicLibraryMxId]' and stid = '$stid'");
            if (empty($record['id'])) {
                //此题未做
                $_POST['topicId'] = $array['topicLibraryMxId'];//试题ID
                $_POST['reply'] = '';
                $this->showNextTopic(true);
            }
        }
    }

    /**
     * 整卷答题---交卷
     */
    public function commitAllPaper()
    {
        $stid = $this->control['stid'];//答题人
        $paperId = $this->post('paperId');//试卷ID
        $paper = query('paper_library', " id = '$paperId'");//试卷信息
        //开始答题记录
        $topicAnswerRecord = query('topic_answer_record', " paperId = '$paper[id]' and stid = '$stid'");
        if (empty($paper['id'])) {
            $json['warn'] = L('topic.table.no_paper');
        } elseif (static::total(array('table' => 'paper_people', "where" => " and orderId = '$paper[id]'")) <= 0) {
            $json['warn'] = L('topic.table.belongStid');
        } elseif ($paper['state'] != '已发布') {
            $json['warn'] = L('topic.table.no_publish');
        } elseif ($topicAnswerRecord['isCommit']) {
            $json['warn'] = L('topic.table.repeatCommit');
        } else {
            $replyArr = $this->post('reply');
            //此试卷所有题目
            $topicArr = find(array('table' => 'paper_library_detail', 'where' => " orderId = '$paper[id]' order by list asc"));
            foreach ($topicArr['array'] as $array) {

                $reply = $replyArr[$array['topicLibraryMxId']] ?? '';
                $_POST['topicId'] = $array['topicLibraryMxId'];//试题ID
                $_POST['reply'] = $reply;
                $_POST['method'] = 'answer';
                $this->showNextTopic(true);
            }
            //计算得分
            $score = find(array('table' => 'topic_answer_record_detail', 'where' => " paperId = '$paperId' and stid = '$stid'", 'sum' => "score"));
            $endTime = strtotime($topicAnswerRecord['startTime']) + 60 * $paper['minute'];
            if ($endTime < time()) {
                $endTime = date('Y-m-d H:i:s', $endTime);
            } else {
                $endTime = $this->time;
            }
            $json['warn'] = update(array(
                'table' => 'topic_answer_record',
                'field' => [
                    'isCommit' => $paper['type'] == '考试' ? 1 : 0,
                    'commitTime' => $endTime,
                    'score' => $score,
                    'state' => $score >= $paper['passMark'] ? '合格' : '不合格',
                ],
                'where' => " id = '$topicAnswerRecord[id]'"
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{paperName}}','{{id}}'],[$this->control['name'],$paper['name'],$paper['id']],L('topic.table.paper_commit'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 逐题答题---交卷
     */
    public function commitPaper()
    {
        $stid = $this->control['stid'];//答题人
        $paperId = $this->post('paperId');//试卷ID
        $paper = query('paper_library', " id = '$paperId'");//试卷信息
        //开始答题记录
        $topicAnswerRecord = query('topic_answer_record', " paperId = '$paper[id]' and stid = '$stid'");
        if (empty($paper['id'])) {
            $json['warn'] = L('topic.table.no_paper');
        } elseif (static::total(array('table' => 'paper_people', "where" => " and orderId = '$paper[id]'")) <= 0) {
            $json['warn'] = L('topic.table.belongStid');
        } elseif ($paper['state'] != '已发布') {
            $json['warn'] = L('topic.table.no_publish');
        } elseif ($topicAnswerRecord['isCommit']) {
            $json['warn'] = L('topic.table.repeatCommit');
        } else {
            //交卷时回答的那一题
            $this->showNextTopic(true);
            //检查未做的题目
            $this->checkNoAnswerTopic($paper, $stid);
            //计算得分
            $score = find(array('table' => 'topic_answer_record_detail', 'where' => " paperId = '$paperId' and stid = '$stid'", 'sum' => "score"));
            $json['warn'] = update(array(
                'table' => 'topic_answer_record',
                'field' => [
                    'isCommit' => $paper['type'] == '考试' ? 1 : 0,
                    'commitTime' => $this->time,
                    'score' => $score,
                    'state' => $score >= $paper['passMark'] ? '合格' : '不合格',
                ],
                'where' => " id = '$topicAnswerRecord[id]'"
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $text = str_replace(['{{staffName}}','{{paperName}}','{{id}}'],[$this->control['name'],$paper['name'],$paper['id']],L('topic.table.paper_commit'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 上一题或下一题
     */
    public function showNextTopic($isCommit = false)
    {
        $stid = $this->control['stid'];//答题人
        $topicId = $this->post('topicId');//试题ID
        $paperId = $this->post('paperId');//试卷ID
        $type = $this->post('type');//pre:上一题  next：下一题
        $paper = query('paper_library', " id = '$paperId'");//试卷信息
        $topic = query('topic_library_detail', " id = '$topicId'");//试题信息
        //开始答题记录
        $topicAnswerRecord = query('topic_answer_record', " paperId = '$paper[id]' and stid = '$stid'");
        $list = $this->post('list');//当前排序号
        $method = $this->post('method');//preview:预览 answer:作答
        $reply = $this->post('reply');//回答
        if ($paper['answerType'] == '逐题答题' && in_array($topic['topicType'], ['主观题'])){
            $reply = $reply[$topicId]??'';
        }
        $maxList = static::total(['table' => self::tableMx, 'where' => " and orderId = '$paperId'"]);//题目总数
        if (empty($paper['id'])) {
            $json['warn'] = L('topic.table.no_paper');
        } elseif (empty($method) || !in_array($method, ['preview', 'answer'])) {
            $json['warn'] = L('topic.table.seeType');
        }else {
            if ($method == 'preview') {
                //预览
                if (!$isCommit && (empty($type) || !in_array($type, ['pre', 'next']))) {
                    $json['warn'] = L('topic.table.goType');
                } else {
                    $json['warn'] = 2;
                }
            } elseif ($method == 'answer') {
                //作答
                if (static::total(array('table' => 'paper_people', "where" => " and orderId = '$paper[id]'")) <= 0) {
                    $json['warn'] = L('topic.table.belongStid');
                } elseif (empty($topicAnswerRecord['id'])) {
                    $json['warn'] = L('topic.table.no_record');
                } elseif ($topicAnswerRecord['isCommit']) {
                    $json['warn'] = L('topic.table.seeRecord');
                } elseif ($paper['state'] != '已发布') {
                    $json['warn'] = L('topic.table.no_publish');
                } elseif (empty($topic['id'])) {
                    $json['warn'] = L('topic.table.find_none_test');
                } elseif (!$isCommit && (empty($type) || !in_array($type, ['pre', 'next']))) {
                    $json['warn'] =  L('topic.table.goType');
                } elseif ($paper['answerType'] == '逐题答题' && $type == 'next' && $reply == '') {
                    $json['warn'] = L('topic.table.answerThis');
                }elseif(!$isCommit && $paper['answerType'] == '逐题答题' && $list == $maxList){
                    $json['warn'] = '这是最后一题了';
                }else {
                    //添加作答记录
                    $this->setAnswer($paper, $topic, $reply, $topicAnswerRecord, $stid);
                    $json['warn'] = 2;
                }
            }

            //重新调整排序
            if (empty($list) || $list <= 0 || !is_numeric($list)) {
                $list = 1;
            } elseif ($list >= $maxList) {
                $list = $maxList;
            }
            if ($type == 'next' && $list < $maxList) {
                $list++;
            } elseif ($type == 'pre' && $list > 1) {
                $list--;
            }
        }
        $json['href'] = root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=previewPaper&method=' . $method . '&id=' . $paperId . '&list=' . $list;
        return json_encode($json, 320);
    }

    /**
     * 添加或更新答题记录
     * @param $paper
     * @param $topic
     * @param $reply
     * @param $topicAnswerRecord
     * @param $stid
     * @return bool|string
     */
    public function setAnswer($paper, $topic, $reply, $topicAnswerRecord, $stid)
    {
        if ($reply === '' || $reply == null) {
            $reply = [];
        } elseif (in_array($topic['topicType'], ['单选题', '判断题', '主观题'])) {
            //重新组装回答形式，便于后面判断回答
            $reply = [$reply];
        }
        //当前试题分数
        $paperLibraryMx = query('paper_library_detail', " orderId = '$paper[id]' and topicLibraryMxId = '$topic[id]'");
        //判断当前回答是否正确
        $bool = $this->judgeAnswer($topic, $reply);
        //答题明细
        $record = query('topic_answer_record_detail', " stid = '$stid' and paperId = '$paper[id]' and topicLibraryMxId = '$topic[id]'");

        if (empty($record['id'])) {
            //没有答题记录
            $json['warn'] = insert(
                array(
                    'table' => 'topic_answer_record_detail',
                    'field' => [
                        'id' => self::getId(),
                        'orderId' => $topicAnswerRecord['id'],
                        'paperId' => $paper['id'],
                        'topicLibraryMxId' => $topic['id'],
                        'topicLibraryId' => $topic['orderId'],
                        'stid' => $stid,
                        'state' => $bool ? 1 : 2,
                        'score' => $bool ? $paperLibraryMx['score'] : 0,
                        'reply' => json_encode($reply, 320),
                        'updateTime' => $this->time,
                        'time' => $this->time,
                    ]
                )
            );
        } else {

            //有答题记录
            $json['warn'] = update(
                array(
                    'table' => 'topic_answer_record_detail',
                    'field' => [
                        'state' => $bool ? 1 : 2,
                        'score' => $bool ? $paperLibraryMx['score'] : 0,
                        'reply' => json_encode($reply, 320),
                    ],
                    'where' => " id = '$record[id]'"
                )
            );

        }
        return json_encode($json, 320);
    }


    /**
     * 判断回答是否正确
     * @param array $array 试题信息
     * @param array $reply 回答
     * @return bool
     */
    public function judgeAnswer(array $array, array $reply): bool
    {
        $itemArr = json_decode($array['item'], true);
        $answer = json_decode($array['answer'], true);
        $answerOrderNo = [];
        foreach ($itemArr as $k => $val) {
            if ($array['topicType'] == '单选题' && $answer[0] == $k) {
                $answerOrderNo[] = $k;
                break;
            } elseif ($array['topicType'] == '多选题' && in_array($k, $answer)) {
                $answerOrderNo[] = $k;
            } elseif ($array['topicType'] == '判断题' && $answer[0] == $k) {
                $answerOrderNo[] = $k;
                break;
            }
        }
        $isRight = false;//回答是否正确
        if ((!empty($reply) && in_array($reply[0], $answerOrderNo) && in_array($array['topicType'], ['单选题', '判断题'])) || ($reply == $answerOrderNo && $array['topicType'] === '多选题')) {
            $isRight = true;
        }
        return $isRight;
    }
}
